<template>
    <div class="content">
        <div >
            <van-swipe class="swiper-flash1" :autoplay="5000" indicator-color="white">
                <van-swipe-item v-for="(image, index) in images" :key="index" @click="showImg">
                    <van-image class="img" fit="cover" lazy-load :src="img(image)">
                        <template v-slot:loading>
                            <van-loading type="spinner" size="20"/>
                        </template>
                    </van-image>

                </van-swipe-item>

            </van-swipe>

            <div class="muber-min-tps">No：{{info.car_number||''}}</div>

            <div class="share-box">
                <van-icon name="arrow-left" @click="$router.back(-1)" class="pull-left"/>

                <van-icon name="share" @click="imgTest" class="pull-right"/>
            </div>

            <div class="page-block">
                <div class="detail-title-min">
                    <div class="min-money pull-left">
                        <span class="money-price">{{info.price}}</span>
                        <span class="money-unite">万</span>
                    </div>

                    <div class="min-tps pull-left" v-if="info.car">指导价：{{info.car.series_max||''}}万元</div>
                </div>
                <div class="detail-title" v-if="info.car">{{info.car.car_name||''}}</div>

                <div class="detail-m-box-box" v-if="info.jr">
                    <div class="detail-m-box">
                        <div class="box-zx">
                            金融专享
                        </div>
                        <div class="hr"></div>

                        <div class="box-txt m">
                            <span class="txt-tit">首付</span>
                            <span class="txt-num">{{info.jr.payment}}</span>
                            <span class="txt-uilt">万</span>
                        </div>

                        <div class="box-txt">
                            <span class="txt-tit">月供</span>
                            <span class="txt-num">{{info.jr.month}}</span>
                            <span class="txt-uilt">元</span>
                        </div>

                        <div class="hr"></div>

                        <a :href="'tel:'+info.jr.phone" class="box-phone">
                            <img src="@/assets/images/car/phone1.svg" class="img" alt="">
                        </a>
                    </div>
                </div>


                <van-divider/>

                <div class="detail-public-title">基本信息</div>
                <ul class="detail-top-box">
                    <li class="item-list">
                        <span class="t">上牌时间：</span>{{stampToDate(info.card_time,2)}}
                    </li>
                    <li class="item-list" style="width: 48%;padding-right: 0">
                        <span class="t">表显里程：</span>{{info.mileage}}万公里
                    </li>
                    <li class="item-list">
                        <span class="t">强险到期：</span>{{stampToDate(info.strong_time,2)}}
                    </li>
                    <li class="item-list">
                        <span class="t">年检到期：</span>{{stampToDate(info.yearly_time,2)}}
                    </li>
                    <li class="item-list" v-if="info.car">
                        <span class="t">排量/变速：</span>{{info.car.car_pl_l||''}}{{checkPL(info.car.car_bsxlx)}}/{{checkBS(info.car.car_bsxlx)}}
                    </li>
                    <li class="item-list" v-if="info.car">
                        <span class="t">排放标准：</span>{{info.car.car_hbbz}}
                    </li>
                    <li class="item-list">
                        <span class="t">车辆性质：</span>{{info.nature}}
                    </li>
                    <li class="item-list">
                        <span class="t">有无抵押：</span>{{info.pledge}}
                    </li>
                    <li class="item-list">
                        <span class="t">过户次数：</span>{{info.transfer_times}}
                    </li>
                    <li class="item-list">
                        <span class="t">牌照归属：</span>{{info.card_come}}
                    </li>
                </ul>

                <van-swipe class="ad-buy-box" style="margin-top: 0" :autoplay="12000" indicator-color="white" v-if="adArr.length>0">
                    <van-swipe-item v-for="(item, index) in adArr" :key="index">
                        <a :href="item.ad_link||'javascript:void(0);'">
                            <van-image class="img" lazy-load :src="img(item.thumb)">
                                <template v-slot:loading>
                                    <van-loading type="spinner" size="20"/>
                                </template>
                            </van-image>
                        </a>
                    </van-swipe-item>
                </van-swipe>

                <!--<div class="detail-public-title">亮点配置</div>

                <ul class="other-tool-box" >
                    <li class="item" v-for="(item,index) in info.add_conf">
                        {{item.title}}
                    </li>
                </ul>

                <router-link :to="{name:'buyToolMini',query:{id:info.id}}" class="detail-more-btn">
                    查看完整配置信息
                </router-link>-->

                <van-divider/>

                <div class="detail-public-title">车况描述</div>
                <div class="detail-content">
                    {{info.content}}
                </div>

                <van-divider/>

                <div class="detail-public-title">看车地点</div>
                <div class="detail-content no-em">
                    <div class="detail-map-box">
                        <div class="map-box-left" id="container"></div>
                        <div class="map-btn" @click="showPicker=true">点击<br/>导航</div>
                    </div>
                    <div>导航地址：{{info.address}}</div>

                    <van-action-sheet v-model="showPicker" :actions="columns" @select="onConfirm" />

                </div>

                <van-divider/>

                <!--<div class="detail-user-box">
                    <img class="img" src="@/assets/images/user/user.svg" alt="">
                    <div class="box-title">
                        <span class="t1">{{info.real_name}}</span>
                        <span class="t2">发布于{{getCity(info.card_come)}}</span>
                    </div>
                    <div class="box-tps">
                        {{info.create_time}}
                    </div>
                </div>-->

                <div class="detail-danger-box">
                    <div class="box-left pull-left">
                        如遇无效、虚假、诈骗、请立即举报<br/>
                        看车时请仔细查看相关证件，切勿提前支付任何费用！
                    </div>
                    <div class="box-right pull-left" @click="fuckThis">
                        <van-icon name="warning" class="ico"/>
                        <div class="tt">举报</div>
                    </div>
                </div>

                <van-divider/>
                <div class="detail-public-title">
                    全部留言
                    <span class="num">({{info.msgCount}})</span>
                </div>


                <div class="list-cell no-border van-clearfix">
                    <template v-for="items in list">

                        <div class="detail-msg-list">
                            <div class="list-head pull-left">
                                <img src="@/assets/images/user/user_g.svg" alt="" class="list-head">
                            </div>

                            <div class="list-right pull-right">
                                <div class="list-header">
                                    <span class="pull-left name">{{subMobie(items.first.user.mobile)}}</span>
                                    <div class="pull-right good-num" @click="msgGood(items.first.id,items.first)">{{items.first.good_numb}}</div>
                                </div>
                                <div class="list-tps">{{items.first.create_time}}</div>

                                <div v-html="getHH(items.child)"></div>

                                <div class="list-content">{{items.first.content}}</div>
                                <div class="list-hh" @click="showMsg(items.first.id)">回复</div>
                            </div>


                        </div>

                    </template>
                </div>
                <a name="msg"></a>
                <infinite-loading :on-infinite="onLoad">
                    <div slot="no-results" class="no-more">没有更多了～</div>
                    <div slot="no-more" class="no-more">没有更多了～</div>
                </infinite-loading>

            </div>

            <van-popup v-model="msgShow" position="bottom" :style="{ height: '50%' }">
                <div class="msg-title">
                    <span v-if="pid>0">回 复 </span>留 言
                    <!--<span class="close" @click="msgShow=false">取消</span>-->
                    <span class="close" @click="carMsg">发布</span>
                </div>
                <van-cell-group>
                    <van-field v-model="message" rows="8" class="msgContent" autosize type="textarea" maxlength="300"
                               placeholder="请输入留言" show-word-limit/>
                </van-cell-group>

                <!--<van-button type="info" class="msg-btn-primary" @click="carMsg">确 定</van-button>-->
            </van-popup>

            <van-popup v-model="shareShow" position="bottom" v-if="!isWechat" :overlay="false" :style="{ height: '20%' }">
                <div class="share-bottom-box">
                    <div class="item" @click="downImg">
                        <div class="item-img down"></div>
                        <div class="item-title">保存图片</div>
                    </div>
                    <!--<div class="item">-->
                        <!--<div class="item-img weixin"></div>-->
                        <!--<div class="item-title">微信</div>-->
                    <!--</div>-->
                    <!--<div class="item">-->
                        <!--<div class="item-img frend"></div>-->
                        <!--<div class="item-title">微信朋友圈</div>-->
                    <!--</div>-->
                </div>

                <van-button type="info" class="msg-btn-primary m" @click="shareShow=false">取消分享</van-button>
            </van-popup>

            <div class="detail-footer-box">
                <div class="d-footer">
                    <div class="footer-left">
                        <div class="item" @click="carCollect">
                            <img src="@/assets/images/icon/sc.svg" alt="" v-if="!collectStatus" class="img">
                            <img src="@/assets/images/icon/sc_par.svg" v-if="collectStatus" alt="" class="img">
                            <div>收藏</div>
                        </div>
                      <!--  <router-link class="item" :to="{name:'buyPk',query:{id:id}}">
                            <img src="@/assets/images/icon/pk.svg" alt="" class="img">
                            <div>对比</div>
                        </router-link>-->
                        <div class="item" @click="showMsg(0)">
                            <img src="@/assets/images/icon/pl.svg" alt="" class="img">
                            <div>留言</div>
                        </div>
                        <div class="item" @click="carGood">
                            <img src="@/assets/images/icon/good.svg" alt="" v-if="!goodMsg" class="img">
                            <img src="@/assets/images/icon/good_par.svg" alt="" v-if="goodMsg" class="img">
                            <div>点赞</div>
                        </div>
                    </div>
                    <a :href="'tel:'+info.mobile" class="footer-btn">拨打电话</a>
                </div>
            </div>
        </div>


        <van-overlay :show="shareShow" @click="shareShow = false">
            <div class="share-wrapper">
                <img :src="imgUrl" class="img" />
            </div>
        </van-overlay>


        <div class="share" style="display: none" id="posterHtml">
            <div class="share-head">
                <div class="head-logo">
                    <img src="@/assets/images/icon/yh_left.svg" class="img" alt="">
                    <img src="@/assets/images/icon/logo.svg" class="img" alt="">
                </div>
                <div class="head-title">
                    优质好车推荐
                    <img src="@/assets/images/icon/yh_right.svg" class="img" alt="">
                </div>

                <div class="head-img">
                    <img class="img" :src="base_img" id="shareImg" crossorigin="anonymous">
                </div>
            </div>

            <div class="share-moeny-box">
                <div class="price">
                    {{info.price}}<span class="unit">万</span>
                </div>

                <div class="box-old-price" v-if="info.car">
                    指导价：{{info.car.series_max||''}}万元
                </div>
                <div class="box-old-price">
                    {{info.car_number||''}}
                </div>
            </div>

            <div class="share-title" v-if="info.car">{{info.car.car_name||''}}</div>

            <div class="detail-m-box-box" v-if="info.jr">
                <div class="detail-m-box">
                    <div class="box-zx">
                        金融专享
                    </div>
                    <div class="hr"></div>

                    <div class="box-txt m">
                        <span class="txt-tit">首付</span>
                        <span class="txt-num">{{info.jr.payment}}</span>
                        <span class="txt-uilt">万</span>
                    </div>

                    <div class="box-txt">
                        <span class="txt-tit">月供</span>
                        <span class="txt-num">{{info.jr.month}}</span>
                        <span class="txt-uilt">元</span>
                    </div>

                    <div class="hr"></div>

                    <a href="" class="box-phone">
                        <img src="@/assets/images/car/phone1.svg" class="img" alt="">
                    </a>
                </div>
            </div>

         <!--   <ul class="other-tool-box" >
                <li class="item" v-for="(item,index) in info.add_conf">
                    {{item.title}}
                </li>
            </ul>-->

            <div class="share-ewm">
                <div class="img" ref="qrCodeUrl" id="qrCodes"></div>
                <div class="txt">长按识别二维码，查看车辆详细信息</div>
            </div>
        </div>
    </div>


</template>

<script>
    import storeJs from 'storejs'
    import { ImagePreview } from 'vant';
    import InfiniteLoading from 'vue-infinite-loading';
    import html2canvas from "html2canvas"
    import QRCode from 'qrcodejs2'

    export default {
        name: "detail",
        components: {
            InfiniteLoading
        },
        data() {
            return {
                images: [],

                id: this.$route.query.id||0,
                adArr: [],
                info: [],

                list: [],
                msgShow: false,
                shareShow: false,
                goodMsg: false,
                collectStatus: false,

                shareStatus: false,

                pid:0, //回复评论ID

                page: 1,

                message: "",
                imgUrl: "",
                base_img: "",
                isWechat: false,

                center: [106.576257, 29.556469], //经度+纬度
                marker: "",
                lat: 29.556469,
                lng: 106.576257,
                loading: true,
                showPicker: false,
                columns: [
                    {name:'高德地图'},
                    {name:'百度地图'},
                    {name:'腾讯地图'}
                ],
                address: [],

                imageShow:false,
                imageStatus:null,
                checkLogin:false,
            }
        },
        computed: {},
        beforeDestroy(){
            var that=this;
            window.addEventListener("popstate",e=>{
                if(that.imageShow){
                    that.imageStatus.close();
                    that.imageShow=!that.imageShow
                }
            },false);
        },
        mounted: function () {
            window.toast=this.$toast;
            window.api=this.$api.car.msgGood;
            window.goodNum=function (id) {
                api({id:id}).then(res=>{
                    var res=res.data;

                    if(res.status){
                        document.getElementById("g"+id).innerHTML=res.data;
                    }else{
                        toast(res.msg);
                    }
                });
            };

            var that=this;
            this.$api.login.checkLogin(function (e) {
                that.checkLogin=true;
            },false);

            //初始化
            this.init();

            //广告
            this.getAd();

            this.creatQrCode();


            window.addEventListener("popstate",e=>{
                if(that.imageShow){
                    that.imageStatus.close();
                    that.imageShow=!that.imageShow
                }
            },false);
            window.scrollTo(0, 0);
        },
        methods: {
            init() {
                var that=this;
                this.$api.car.detail(this.id).then(res => {
                    var res = res.data;
                    this.info = res.data;
                    that.center = [res.data.lng,res.data.lat];
                    that.address = res.data.address.split('-');
                    that.lat=res.data.lat;
                    that.lng=res.data.lng;

                    if(this.info.head_img!='' && this.info.head_img!=null){
                        this.images.push(this.info.head_img)
                    }

                    if (this.info.img_list.length == 0) {
                        this.images.push(this.info.car.series_thumb)
                    } else {
                        this.info.img_list.find(res=>{
                            this.images.push(res.thumb);
                        });
                    }

                    if(this.info.collectStatus>0){
                        this.collectStatus=true;
                    }
                    if(this.info.goodStatus>0){
                        this.goodMsg=true;
                    }

                    this.checkLable();
                    that.adMap();

                    var url="";
                    if(this.info.head_img!='' && this.info.head_img!=null){
                        url=this.info.head_img;
                    }else{
                        if(this.info.img_list.length>0){
                            url=this.info.img_list[0]["thumb"];
                        }else if(this.info.car){
                            url=this.info.car.series_thumb;
                        }
                    }

                    if (url!=""){
                        var m=that.img(url)+"?"+new Date().getTime();
                        that.getUrlBase64(m, 'png', function (base64) {
                            that.base_img=base64;
                        });
                    }



                });

                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    this.isWechat=true;
                } else {
                    this.isWechat=false;
                }
            },
            getUrlBase64(url, ext, callback){
                var canvas = document.createElement("canvas");   //创建canvas DOM元素
                var ctx = canvas.getContext("2d");
                var img = new Image;
                img.crossOrigin = 'Anonymous';
                img.src = url;
                img.onload = function () {
                    canvas.height = 435; //指定画板的高度,自定义
                    canvas.width = 655; //指定画板的宽度，自定义
                    ctx.drawImage(img, 0, 0, 655, 435); //参数可自定义
                    var dataURL = canvas.toDataURL("image/" + ext);
                    callback.call(this, dataURL); //回掉函数获取Base64编码
                    canvas = null;
                };
            },
            onLoad($state) {
                var that=this;

                this.$api.car.msg(that.id,that.page,{}).then(res=>{
                    res=res.data;

                    if (res.data.data.length) {
                        that.list.push(...res.data.data);
                        that.page++;

                        $state.loaded();
                    } else {
                        $state.complete();
                    }
                });
            },

            //广告
            getAd() {
                this.$api.index.getAd({
                    pid: 2
                }).then(res => {
                    res = res.data;
                    this.adArr = res.data;
                });
            },

            //留言点赞
            msgGood(id,item){
                if(storeJs('msg'+id)){
                    this.$toast('重复点赞无效！');
                    return false;
                }else{
                    this.$api.car.msgGood({id:id}).then(res=>{
                        var res=res.data;

                        if(res.status){
                            storeJs('msg'+id,"1");
                            item.good_numb=res.data;
                        }else{
                            this.$toast(res.msg);
                        }
                    });
                }
            },

            //留言点赞
            carGood(){
                let that=this;
                if(!that.checkLogin){
                    this.$api.login.checkLogin();
                    return true;
                }
                that.$api.car.carGood({id:that.id}).then(res=>{
                    var res=res.data;

                    if(res.status){
                        that.goodMsg=that.goodMsg?false:true;
                    }else{
                        that.$toast(res.msg);
                    }
                });
            },

            //留言点赞
            carMsg(){
                if(storeJs('userCarMsg_'+this.id+"_"+this.pid)){
                    var curTime = new Date();
                    var endTime = storeJs('userCarMsg_'+this.id+"_"+this.pid);

                    if(curTime<=endTime){
                        // this.$toast('频繁操作，请稍后再试！');
                        // return false;
                    }
                }

                if(this.message==""){
                    this.$toast('请填写留言内容！');
                    return false;
                }

                this.$api.car.carMsg({
                    id:this.id,
                    pid:this.pid,
                    msg:this.message
                }).then(res=>{
                    var res=res.data;

                    if(res.status){
                        this.$toast("留言审核中！");
                        this.msgShow=false;
                        this.message="";

                        var date=new Date();
                        var min=date.getMinutes();
                        date.setMinutes(min+10);

                        storeJs('userCarMsg_'+this.id+"_"+this.pid,`${Date.parse(date)}`);
                    }else{
                        this.$toast(res.msg);
                    }
                });
            },

            //收藏
            carCollect(){
                let that=this;
                if(!that.checkLogin){
                    this.$api.login.checkLogin();
                    return true;
                }

                var carId=that.info.car?that.info.car.car_id:0;
                that.$api.car.userCollect({id:that.id,car_id:carId}).then(res=>{
                    var res=res.data;

                    if(res.status){
                        //this.$toast("收藏成功！");
                        if(that.collectStatus){
                            that.collectStatus=false;
                        }else{
                            that.collectStatus=true;
                        }
                    }else{
                        that.$toast(res.msg);
                    }
                });
            },

            showMsg(pid=0){
                let that=this;
                if(!that.checkLogin){
                    this.$api.login.checkLogin();
                    return true;
                }

                that.msgShow=true;
                that.pid=pid;
                console.log(that.pid)
            },

            //查看图片
            showImg(){
                var arr=[];

                var that=this;

                this.images.find(res=>{
                    arr.push(this.img(res))
                });

                that.imageShow=true;
                window.history.pushState(null,null,'#');

                this.imageStatus = ImagePreview({
                    images:arr,
                    closeOnPopstate:true,
                    onClose:function (e) {
                        that.imageShow=false;
                        //that.$router.go(-1);
                    }
                });
            },

            //举报功能
            fuckThis(){
                this.$dialog.confirm({
                    message: "您确定要举报此辆车吗？"
                }).then(() => {
                    this.$toast("举报成功！");
                }).catch(()=>{});
            },

            getHH(list){
                if(list.length>0){
                var str='<div class="list-floor">';
                list.find((item,index)=>{
                    if(index>0) str+='<div class="list-floor">';
                });

                list.find((item,index)=>{
                    if(index>0) str+='</div>';
                    str+='<div class="floor-list" name="'+item.id+'">';
                    str+='<div class="floor-list-header">'+this.subMobie(item.user.mobile)+'</div>';
                    str+='<div class="floor-list-tps">';
                    str+=(index+1)+'楼 '+item.create_time;
                    str+='<div class="pull-right floor-good-num" onclick="goodNum('+item.id+')" id="g'+item.id+'">'+item.good_numb+'</div>';
                    str+='</div>';
                    str+='<div class="floor-list-content">'+item.content+'</div>';
                    str+='</div>';
                });
                str+='</div>';
                }

                return str;

            },

            imgTest(){
                $("#posterHtml").show();

                this.$toast.loading({
                    message: '加载中...',
                    forbidClick: true,
                    overlay:true,
                    duration:0
                });

                // 生成海报
                const that = this;
                const domObj = document.getElementById('posterHtml');

                setTimeout(function () {
                    html2canvas(domObj,{
                        useCORS: true,//允许加载跨域的图片
                        tainttest:true, //检测每张图片都已经加载完成
                    }).then(function(canvas) {
                        // 在微信里,可长按保存或转发
                        $("#posterHtml").hide();
                        var content = canvas.toDataURL('image/png');
                        that.imgUrl=content;
                        that.shareShow=true;
                        that.$toast.clear();

                        // that.$api.index.shares({content:content}).then(res=>{
                        //     that.imgUrl=that.img(res.data.data);
                        //     that.shareShow=true;
                        //     that.$toast.clear();
                        // });
                    })
                },500);


            },

            /**
             * 生成二维码
             */
            creatQrCode() {
                var id=this.id;
                var qrcode = new QRCode(this.$refs.qrCodeUrl, {
                    text: 'http://www.xb2sc.cn/#/detail?id='+id, // 需要转换为二维码的内容
                    width: $("#qrCodes").width(),
                    height: $("#qrCodes").height(),
                    colorDark: '#000000',
                    colorLight: '#ffffff',
                    correctLevel: QRCode.CorrectLevel.H
                });
                setTimeout(function () {
                    $("#qrCodes img").css({"width":"100%","height":"100%"});
                },300)

            },

            checkLable(){
                if(this.info.car){
                    var car = this.info.car;

                    if(car.car_zczdlx.indexOf('电子')!=-1) this.info.add_conf.push({title:car.car_zczdlx});
                    if(car.car_tyjcgn.indexOf('●')!=-1) this.info.add_conf.push({title:"胎压监测功能"});
                    if(car.car_abs.indexOf('●')!=-1) this.info.add_conf.push({title:"ABS防抱死"});
                    if(car.car_bxhz.indexOf('●')!=-1) this.info.add_conf.push({title:"并线辅助"});
                    if(car.car_dphj.indexOf('●')!=-1) this.info.add_conf.push({title:"陡坡缓降"});
                    if(car.car_zdzc.indexOf('●')!=-1) this.info.add_conf.push({title:"自动驻车"});
                    if(car.car_sphz.indexOf('●')!=-1) this.info.add_conf.push({title:"上坡辅助"});
                    if(car.car_qhld.indexOf('●')!=-1) this.info.add_conf.push({title:"驻车雷达"});
                    if(car.car_ba.indexOf('●')!=-1) this.info.add_conf.push({title:"刹车辅助(EBA/BAS/BA等)"});
                    if(car.car_gyhbx.indexOf('●')!=-1) this.info.add_conf.push({title:"感应后备厢"});
                    if(car.car_wysqd.indexOf('●')!=-1) this.info.add_conf.push({title:"无钥匙启动系统"});
                    if(car.car_wysjr.indexOf('●')!=-1) this.info.add_conf.push({title:"无钥匙进入功能"});
                }
            },

            /**
             * 下载图片
             */
            downImg(){
                var that=this;
                if(typeof window.Base64ImageSaverPlugin == 'undefined') {
                    this.downloadFile('share.png', this.imgUrl);
                }else{
                    var permissions = cordova.plugins.permissions;
                    permissions.checkPermission(permissions.WRITE_EXTERNAL_STORAGE, function(s) {

                        if (!s.hasPermission) {
                            //没有权限
                            //app申请写入权限
                            permissions.requestPermission(permissions.WRITE_EXTERNAL_STORAGE, function(s) {
                                if (s.hasPermission) {
                                    //申请成功
                                    that.don();
                                }
                                else {
                                    //申请失败
                                    that.$toast("保存失败，请查看是否有权限！");
                                    that.shareShow=false;
                                    //alert("失败");
                                }
                            }, function(error) {
                                that.$toast("保存失败，请查看是否有权限！");
                                that.shareShow=false;
                                //alert(error);
                            });
                        } else {
                            //拥有权限
                            that.don();
                        }
                    }, function(error) {
                        that.$toast("保存失败，请查看是否有权限！");
                        that.shareShow=false;
                        //alert("fuck");
                    });
                }
            },

            don(){
                var that=this;
                window.Base64ImageSaverPlugin.saveImageDataToLibrary(
                    function(msg){
                        that.$toast("成功保存到相册！");
                        that.shareShow=false;
                    },
                    function(err){
                        that.$toast("保存失败，请查看是否有权限！");
                        that.shareShow=false;
                        console.log(err);
                    },
                    that.imgUrl
                );
            },

            //下载
            downloadFile(fileName, content) {
                let aLink = document.createElement('a');
                let blob = this.base64ToBlob(content); //new Blob([content]);

                let evt = document.createEvent("HTMLEvents");
                evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型，是否冒泡，是否阻止浏览器的默认行为
                aLink.download = fileName;
                aLink.href = URL.createObjectURL(blob);
                // aLink.dispatchEvent(evt);
                 aLink.click()
                this.shareShow=false;
                //aLink.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));//兼容火狐
            },
            //base64转blob
            base64ToBlob(code) {
                let parts = code.split(';base64,');
                let contentType = parts[0].split(':')[1];
                let raw = window.atob(parts[1]);
                let rawLength = raw.length;

                let uInt8Array = new Uint8Array(rawLength);

                for (let i = 0; i < rawLength; ++i) {
                    uInt8Array[i] = raw.charCodeAt(i);
                }
                return new Blob([uInt8Array], {type: contentType});
            },
            adMap() {
                this.loading = false;
                //初始化地图
                var map = new AMap.Map("container", {
                    zoom: 14, //缩放级别
                    center: this.center //设置地图中心点
                    //resizeEnable: true,  //地图初始化加载定位到当前城市
                });
                //获取初始中心点并赋值
                var currentCenter = map.getCenter(); //此方法是获取当前地图的中心点
                this.center = [currentCenter.lng, currentCenter.lat]; //将获取到的中心点的纬度经度赋值给data的center
                console.log(this.center);

                //创建标记
                this.marker = new AMap.Marker({
                    position: new AMap.LngLat(currentCenter.lng, currentCenter.lat) // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                });
                // 将创建的点标记添加到已有的地图实例：
                map.add(this.marker);
            },
            onConfirm(value){
                this.choose(value.name);
                this.showPicker = false;
            },
            onChange(picker,value){
                this.choose(value);
                //this.showPicker = false;
            },

            choose(names) {  //item是传递过来的高德地图、百度地图、腾讯地图
                var that=this;

                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    this.$toast("浏览器不支持导航，请下载APP后再试");
                    return false;
                }

                if(typeof(appAvailability)==null || typeof(appAvailability)=="undefined" || typeof(appAvailability)==undefined){
                    this.$toast("浏览器不支持导航，请下载APP后再试");
                    return false;
                }

                var baiduPackageName = "com.baidu.BaiduMap";//百度地图包名
                var gaodePackageName = "com.autonavi.minimap";//高德地图包名
                var destination = this.center;//获取vuex中的想去目的地的经纬度参数
                var u = navigator.userAgent;//判断是android系统还是IOS系统
                var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
                var isIOS = false; //ios终端

                if(!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){
                    isIOS=true;
                }
                if(!isAndroid && !isIOS){
                    this.$toast("浏览器不支持导航，请下载APP后再试");
                    return false;
                }

                var Destination = that.address[0];
                var geoCoordinates = that.address[0];
                if (names == "高德地图") {
                    let scheme;
                    if (isAndroid == true) {
                        scheme = 'com.autonavi.minimap';//获取对应系统的高德地图包名
                    }
                    else {
                        scheme = 'iosamap://';
                    }
                    appAvailability.check(scheme, function () {//使用插件的检测包名的函数，判断手机是否安装该第三方APP!!!!!最重要的地方
                        if (isAndroid == true) {
                            var sApp = startApp.set({
                                "action": "ACTION_VIEW",
                                "category": "CATEGORY_DEFAULT",
                                "type": "text/css",
                                "package": "com.autonavi.minimap",
                                "uri": "amapuri://route/plan/?dlat=" + that.lat + "&dlon=" + that.lng + "&dname=" + Destination + "&dev=0&t=0",//传递经纬度参数
                                "flags": ["FLAG_ACTIVITY_CLEAR_TOP", "FLAG_ACTIVITY_CLEAR_TASK"],
                                "intentstart": "startActivity"
                            });
                            sApp.start(function () { /* success */
                                //alert("OK");
                            }, function (error) { /* fail */
                                this.$toast(error);
                            });
                        } else {//若是IOS,则调起ios版本的
                            window.location.href = "iosamap://navi?sourceApplication=applicationName&poiname=" + Destination + "&poiid=BGVIS&lat=" + that.lat + "&lon=" + that.lng + "&dev=1&style=2";
                        }
                    }, function () {//若没有相应安装相应第三方APP，则弹出链接，提醒下载相应APK
                        if (isAndroid == true) {
                            cordova.InAppBrowser.open("http://amapdownload.autonavi.com/down6/C3060/Amap_V10.35.1.2655_android_C3060_(Build2004222234).apk", '_system', 'hardwareback=no')
                        }
                        else {
                            window.location.href = "itms-apps://itunes.apple.com/cn/app/%E9%AB%98%E5%BE%B7%E5%9C%B0%E5%9B%BE-%E7%B2%BE%E5%87%86%E5%9C%B0%E5%9B%BE-%E5%AF%BC%E8%88%AA%E5%87%BA%E8%A1%8C%E5%BF%85%E5%A4%87/id461703208?mt=8";
                        }
                    });
                }
                else if (names == "百度地图") {
                    let scheme;
                    if (isAndroid == true) {
                        scheme = 'com.baidu.BaiduMap';
                    }
                    else {
                        scheme = 'baidumap://';
                    }
                    appAvailability.check(scheme, function () {//success callback
                        if (isAndroid == true) {
                            var sApp = startApp.set({
                                /* params */
                                "action":"ACTION_VIEW",
                                "category":"CATEGORY_DEFAULT",
                                "type":"text/css",
                                "package":"com.baidu.BaiduMap",
                                "uri": "baidumap://map/direction?destination=name:"+Destination+"|latlng:"+that.lat+","+that.lng+"&mode=driving",
                                "flags":["FLAG_ACTIVITY_CLEAR_TOP","FLAG_ACTIVITY_CLEAR_TASK"],
                                "intentstart":"startActivity"
                            });
                            sApp.start(function () { /* success */
                                //alert("OK");
                            }, function (error) { /* fail */
                                this.$toast(error);
                            });
                        }
                        else {
                            window.location.href = "baidumap://map/direction?origin=" + geoCoordinates + "&destination=" + Destination + "&mode=driving&src=webapp.navi.yourCompanyName.yourAppName";
                        }
                    }, function () {//
                        if (isAndroid == true) {
                            cordova.InAppBrowser.open("https://downapp.baidu.com/baidumap/AndroidPhone/10.24.8.1/1/1012337a/20200428220223/baidumap_AndroidPhone_10-24-8-1_1012337a.apk?responseContentDisposition=attachment%3Bfilename%3D%22baidumap_AndroidPhone_1012337a.apk%22&responseContentType=application%2Fvnd.android.package-archive&request_id=1588356464_2475875955&type=static", '_system', 'hardwareback=no')
                        }
                        else {
                            window.location.href = "itms-apps://itunes.apple.com/cn/app/%E7%99%BE%E5%BA%A6%E5%9C%B0%E5%9B%BE-%E6%99%BA%E8%83%BD%E5%AF%BC%E8%88%AA%E8%B7%AF%E7%BA%BF%E8%A7%84%E5%88%92%E6%97%85%E6%B8%B8%E5%87%BA%E8%A1%8C/id452186370?mt=8";
                        }
                    });
                }
                else if (names == "腾讯地图") {
                    let scheme;
                    if (isAndroid == true) {
                        scheme = 'com.tencent.map';
                    }
                    else {
                        scheme = 'sosomap://';
                    }
                    appAvailability.check(scheme, function () {//success callback
                        if (isAndroid == true) {
                            var sApp = startApp.set({
                                /* params */
                                "action": "ACTION_VIEW",
                                "category": "CATEGORY_DEFAULT",
                                "type": "text/css",
                                "package": "com.tencent.map",
                                "uri": "qqmap://map/routeplan?type=drive&to=" + Destination + "&tocoord=" + that.lat + "," + that.lng + "&coord_type=1&policy=0",
                                "flags": ["FLAG_ACTIVITY_CLEAR_TOP", "FLAG_ACTIVITY_CLEAR_TASK"],
                                "intentstart": "startActivity"
                            });
                            sApp.start(function () { /* success */
                                //alert("OK");
                            }, function (error) { /* fail */
                                this.$toast(error);
                            });
                        }
                        else {
                            window.location.href = "qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&to=" + Destination + "&tocoord=" + that.lat + "," + that.lng + ""
                        }
                    }, function () {//
                        if (isAndroid == true) {
                            cordova.InAppBrowser.open("https://qqmap-1251316161.file.myqcloud.com/mapCosApiUpload/apk/8.13.2.722/tencentmap_8.13.2.722_android_00002.apk", '_system', 'hardwareback=no')
                        } else {
                            window.location.href = "itms-apps://itunes.apple.com/cn/app/%E8%85%BE%E8%AE%AF%E5%9C%B0%E5%9B%BE-%E8%B7%AF%E5%86%B5%E7%B2%BE%E5%87%86%E5%87%BA%E8%A1%8C%E5%BF%85%E5%A4%87%E7%9A%84%E5%AF%BC%E8%88%AA%E8%BD%AF%E4%BB%B6/id481623196?mt=8"
                        }
                    })
                }
                else if (names == "苹果地图") {
                    window.location.href = "http://maps.apple.com/?daddr=" + Destination + "&dirflg=d&t=h"
                }
                else {
                    this.showPicker = false;
                }
            },

            checkBS(v){
                var m=v||'';
                if(m.indexOf('AT')!=-1 || m.indexOf('at')!=-1){
                    return "AT";
                }else if(m.indexOf('MT')!=-1 || m.indexOf('mt')!=-1){
                    return "MT";
                }else if(m.indexOf('自')!=-1){
                    return "自动";
                }else if(m.indexOf('手')!=-1){
                    return "手动";
                }
            },

            checkPL(v){
                var m=v||'';
                if(m.indexOf('AT')!=-1 || m.indexOf('at')!=-1){
                    return "T";
                }else if(m.indexOf('MT')!=-1 || m.indexOf('mt')!=-1){
                    return "T";
                }else{
                    return "L";
                }
            }

        },
    }
</script>

<style lang="scss" scoped>
    @import "../../assets/scss/index.scss";
</style>
